package org.learn.spring_quartz.service;

import org.learn.spring_quartz.dto.QueryParams;
import org.learn.spring_quartz.dto.RequestData;
import org.learn.spring_quartz.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Service
public class ApiServiceImpl implements ApiService {

    @Autowired
    private WebClient webClient;

    /**
     * post请求
     * @param requestData
     * @return
     */
    @Override
    public Result postData(RequestData requestData) {
        return webClient.post().uri(requestData.getUri()).bodyValue(requestData.getBody()).retrieve().onStatus(status -> status.value() == 401,
                clientResponse -> Mono.error(new RuntimeException("401 未授权"))).bodyToMono(Result.class).block();
    }

    /**
     * get请求
     * @param queryParams
     * @return
     */
    @Override
    public Result fetchData(QueryParams queryParams) {
        return webClient.get().uri(uriBuilder -> uriBuilder.path(queryParams.getUri()).queryParams(queryParams.getBody()).build()).retrieve().bodyToMono(Result.class).block();
    }
}
